package main

import (
	"encoding/json"
	"fmt"
)

type Monster struct {
	Name     string `json:"N"`
	Age      int
	Birthday string
	Sal      float64
	Skill    string
}

func testStruct() {
	monster := Monster{
		Name:     "牛魔王",
		Age:      10000,
		Birthday: "2000-12-17",
		Sal:      8000.0,
		Skill:    "牛魔拳",
	}
	data, err := json.Marshal(monster)
	if err != nil {
		fmt.Println("序列化错误 err=", err)
	}
	fmt.Println("monster序列化后，", string(data))
}
func testMap() {
	var a map[string]interface{}
	a = make(map[string]interface{})
	a["name"] = "红孩儿"
	a["age"] = 30
	a["address"] = "洪崖洞"
	data, err := json.Marshal(a)
	if err != nil {
		fmt.Println("序列化错误 err=", err)
	}
	fmt.Println("a序列化后，", string(data))
}
func testSlice() {
	var slice []map[string]interface{}
	var m1 map[string]interface{}
	m1 = make(map[string]interface{})
	m1["name"] = "jack"
	m1["age"] = 80
	m1["address"] = "杭州"
	slice = append(slice, m1)
	var m2 map[string]interface{}
	m2 = make(map[string]interface{})
	m2["name"] = "summer"
	m2["age"] = 20
	m2["address"] = "上海"
	slice = append(slice, m2)
	data, err := json.Marshal(slice)
	if err != nil {
		fmt.Println("序列化错误 err=", err)
	}
	fmt.Println("slice序列化后，", string(data))
}
func testFloat() {
	var num1 float64 = 234.567
	data, err := json.Marshal(num1)
	if err != nil {
		fmt.Println("序列化错误 err=", err)
	}
	fmt.Println("num1序列化后，", string(data))
}
func unmarshalStruct() {
	str := "{\"N\":\"牛魔王\",\"Age\":500,\"Birthday\":\"2000-12-17\",\"Sal\":8000,\"Skill\":\"牛魔拳\"}"
	var monster Monster
	err := json.Unmarshal([]byte(str), &monster)
	if err != nil {
		fmt.Println("unmarshal err=", err)
	}
	fmt.Printf("反序列化后 monster=%v monster.Name=%v", monster, monster.Name)
}
func main() {
	testStruct()
	testMap()
	testSlice()
	testFloat()
	unmarshalStruct()
}
